﻿using BoardBroker;
using ComLib.ComType;
using CoreBroker;
using KWindow.KPageCore;
using LogLib;
using System;
using System.Diagnostics;
using System.Threading;

namespace IPCPages
{
    public class ProcessMakePreparations : PageProcessBase<ProcessMakePreparations>
    {
        private Readying _ready = null;

        private BoardControl _board = null;

        private CapturerBroker capturerBroker1;

        private bool Ready = false;

        private int _actionIndex = 0;

        private ProcessMakePreparations() : base()
        {
            _board = BoardControl.Instance;
        }

        public override void Init()
        {
            base.Init();
        }

        public override void Exit()
        {
            base.Exit();
        }

        public override void InitData()
        {
            _actionIndex = GetValue<int>("ActionIndex");
            _actionIndex++;
            SetValue("ActionIndex", _actionIndex);
            base.InitData();
            // 清理上次拍照记录
            RemoveKey("PhotoTakenResult");
            RemoveKey("TakenPhotos");
            Ready = false;
            capturerBroker1 = GetValue<CapturerBroker>("Capturer");
            _ready = new Readying(SynchronizationContext.Current, capturerBroker1);         
            _ready.TaskAborted += OnTaskAborted;
            _ready.ReadyTaskCompleted += OnReadyTaskCompleted;
            _ready.App = GetValue<ApplyTo>("ApplyTo");//照片类型
            SetValue("Readying", _ready);
        }

        public override void UpdateData()
        {
            base.UpdateData();
        }

        public override void StartWork()
        {
            if(MainPage == null)
            {
                return;
            }
            if (MainPage.InvokeRequired)
            {
                Action handler = new Action(StartWork);
                MainPage.Invoke(handler);
                return;
            }
            base.StartWork();
            _board.StartWorking();
            capturerBroker1.RestartWork();           
            int delaySecond = 3;
            // 重拍增加预览时间
            if (_actionIndex > 1)
            {
                delaySecond = 5;
            }
            else
            {
                // 单人首次拍照使用默认参数
                ComLib.ComFun.AsyncTask.Delay(2, () => capturerBroker1.SetDefalutProperties());
            }
            ComLib.ComFun.AsyncTask.Delay(delaySecond, () => StartReadying());           
        }

        public override void StopWork()
        {
            _ready.StopWork();
            base.StopWork();
        }

        public override void PlayWelcomeVoice()
        {
            base.PlayWelcomeVoice();
        }

        /// <summary>
        /// 启动准备拍照控制对象
        /// </summary>
        public void StartReadying()
        {
            if (!IsRunning)
            {
                return;
            }
            if (MainPage.InvokeRequired)
            {
                Action handler = new Action(StartReadying);
                MainPage.Invoke(handler);
                return;
            }
            if (!Ready)
            {                
                Ready = true;
                //_ready.StartWork();
                ToNext();
            }
        }

        private void OnReadyTaskCompleted(object sender, ReadyTaskCompletedEventArgs e)
        {
            if (e.FrontDetected)
            {
                Log.WriteAsync("正脸识别成功, 进入正式拍照页面!");
            }
            else
            {
                Log.WriteAsync("正脸检测不合格, 强制进入正式拍照页面!");
            }
            if (IsRunning)
            {
                ClearData();
                StopWork();
                ToNext();
            }
        }

        private void OnTaskAborted(object sender, ReadyTaskAbortedEventArgs e)
        {
            if (MainPage.InvokeRequired)
            {
                ReadyTaskAbortedEventHandler handler
                    = new ReadyTaskAbortedEventHandler(OnTaskAborted);
                MainPage.Invoke(handler, new object[] { sender, e });
                return;
            }
            string error = "准备拍照失败:" + e.AbortReason;
            Log.WriteAsync(error);
            _board.StopWorking();
            capturerBroker1.StopCapturer();
            NotifyClientTakePhotoAborted(error);
            ClearData();          
            ToHome();
        }

        private void NotifyClientTakePhotoAborted(string error)
        {
            if (Job != null)
            {
                Job.Abort(error);
            }
        }
    }
}
